package cn.rui.security;

import cn.rui.common.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 浏览器环境下登录失败的处理器
 *
 * @author yuyi
 * @version 1.0
 *
 */

@Component
public class BrowserAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	/**
	 * (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {

		//response.setStatus(HttpStatus.BAD_REQUEST.value());
		response.setHeader("Content-type", "text/html;charset=UTF-8");

		//httpServletResponse.getWriter().println("{\"code\":403,\"message\":\"小弟弟，你没有权限访问呀！\",\"data\":\"\"}");
		//httpServletResponse.getWriter().println (result);
		//httpServletResponse.getWriter().flush();

		String jsonString = JSON.toJSONString (Result.getFailure ("登录失败，账号或密码错误"));
		PrintWriter writer = response.getWriter ();
		writer.append (jsonString);
		writer.flush ();

		//response.getWriter().append(exception.getMessage());
	}
}
